package com.gxuwz.medical.web.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gxuwz.medical.dao.*;
import com.gxuwz.medical.domain.area.Area;
import com.gxuwz.medical.domain.payment.Payment;
import com.gxuwz.medical.domain.payment.Payperiod;
import com.gxuwz.medical.domain.person.Person;
import com.gxuwz.medical.exception.PayperiodUnfoundException;
import com.gxuwz.medical.tools.DateUtil;
import java.io.*;
import jxl.Workbook;
import jxl.write.*;
import jxl.write.biff.RowsExceededException;
/**
 * 缴费管理控制模块
 * 
 * @author 演示
 * 
 */
public class PaymentServlet extends BaseServlet {
	
	private AreaDao areaDao;
	private PersonDao personDao;
	private static final String LIST_JSP = "/page/payment/payment_list.jsp";
	private static final String INPUT_JSP = "/page/payment/payment_input.jsp";
	private static final String CHOOSE_JSP = "/page/payment/payment_choose.jsp";
	private static final String MEMBERS_JSP = "/page/payment/payment_member.jsp";
	private static final String PRINT_JSP = "/page/payment/payment_print.jsp";
	

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String m = req.getParameter("m");// 请求处理动作类型:
		String url = ERROR_PATH;
		try {
			if ("input".equals(m)) {
				url = input(req, resp);
			}else if ("choose".equals(m)) {
				url = choose(req, resp);
			}else if ("members".equals(m)) {
				url = members(req, resp);
			}else if ("print".equals(m)) {
				url = print(req, resp);
			}else if ("pay".equals(m)) {
				url = pay(req, resp);
			}else if ("list".equals(m)) {
				url = input(req, resp);
			}else if ("gopay".equals(m)) {
				url = gopay(req, resp);
			}else if ("printpay".equals(m)) {
				url = printpay(req, resp);
			}else if ("paydo".equals(m)) {
				url = paydo(req, resp);
			}
		}catch(PayperiodUnfoundException e){
        	e.printStackTrace();
        	req.setAttribute("error", e.getMessage());
        }catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("error", e.getMessage());
		}
		// 跳转至目标页面
		process(req, resp, url);
	}

	/**
	 * 缴费初始化界面
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	private String gopay(HttpServletRequest req, HttpServletResponse resp) {
		return "/page/payment/payment_pay.jsp";
		
		
	}
	private String printpay(HttpServletRequest req, HttpServletResponse resp) throws RowsExceededException, WriteException, IOException, SQLException {
		this.printdata(req, resp,true);
		return "/page/payment/payment_pay.jsp";
		
		
	}
	private String paydo(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		Payment payment=new Payment();
		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");  
        Date cur = new Date();
        String curtime=ft.format(cur);
        String curyear=curtime.substring(0, 4);
        try {
			Payperiod period=new Payperiod(Integer.valueOf(curyear));
			System.out.println("sjkafl"+period.available());
			if(!period.available()) {
				req.setAttribute("error", "现在不是缴费时间");
				return "/error.jsp";
			}
			else {
				payment.setFamicode(req.getParameter("id"));
				payment.setPerscode(req.getParameter("perscode"));
				payment.setPayCost(period.getAmount());
				payment.setPaytime(new Date());
				payment.setRunyear(Integer.valueOf(curyear));
				String crea=(String)req.getSession().getAttribute("userName");
				payment.setCreator(crea);
			    payment.addPayment();
			    
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (PayperiodUnfoundException e) {
			// TODO Auto-generated catch block
			req.setAttribute("error", "payperiodUnfound现在不是缴费时间");
			e.printStackTrace();
			return "/error.jsp";
		}
        
		this.printdata(req, resp,false);
		return "/page/payment/payment_pay.jsp";
		
	}
	private String input(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
        //初始化村列表
		String town=(String)req.getSession().getAttribute("agencode");
		List<Area> villages=areaDao.findChildArea(town, 3);
		req.setAttribute("villages", villages);
		//初始化村列表第一个元素对应的组列表
	    if(villages!=null&&!villages.isEmpty()){
	    	Area area=villages.get(0);
	    	String groupNo=area.getAreacode();
	    	List<Area> groups=areaDao.findChildArea(groupNo, 4);
	    	req.setAttribute("groups", groups);
	    }
		return LIST_JSP;
	}
	/**
	 * 查找户主信息
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	private String choose(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		//村编号
		String village=req.getParameter("village");
		//组编号
		String group=req.getParameter("group");
		//户主姓名
		String persname=req.getParameter("persname");
		//行政区域编号默认等于村编号
		String areacode=village;
		//如果组编号不为空，行政区域编号等于组编号
		if(group!=null&&!"".equals(group)){
			areacode=group;
		}
		//根据村编号+组编号+户主编号查找户主信息
		List<Person> hostList=personDao.findHostByName(persname, areacode);
		req.setAttribute("hostList", hostList);
		return CHOOSE_JSP;
		
	}
	/**
	 * 查询未交费人员列表
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	private String members(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		//缴费年份，默认为当前系统时间对应的年份
		int payYear=DateUtil.getYear(new java.util.Date());
		String famicode=req.getParameter("famicode");
		//根据家庭编号+缴费年度查找未缴费人员名单
        List<Person> persons=personDao.findUnpayList(famicode, payYear);
        //根据年份读取并显示缴费标准
        Payperiod payperiod=new Payperiod(payYear);
        req.setAttribute("amount", payperiod.getAmount());
        req.setAttribute("persons", persons);
		return MEMBERS_JSP;
	}
	/**
	 * 缴费过程
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	private String pay(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		//获取选中的缴费成员名单
        String[] perscodes=req.getParameterValues("perscodes");
        Payment payment=new Payment();
        String creator=(String)req.getSession().getAttribute("userName");
        //缴费年份，默认为当前系统时间对应的年份
      	int payYear=DateUtil.getYear(new java.util.Date());
      	//缴费时间设置
        Payperiod payperiod=new Payperiod(payYear);
        //执行缴费过程
        payment.addPay(perscodes, payperiod, creator);
        
		return input(req, resp);
	}
	private String print(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {

		return PRINT_JSP;
	}

	@Override
	public void init() throws ServletException {
		 areaDao=new AreaDao();
		 personDao=new PersonDao();
	}
public void printdata(HttpServletRequest req, HttpServletResponse resp,boolean flag) throws IOException, RowsExceededException, WriteException, SQLException {
	WritableWorkbook wwb = null;
	//插件可写入的excel工作表
	String fileName = "D://paylist.xls";
	File file = new File(fileName);
	if (!file.exists()) {
		file.createNewFile();
	}
	wwb =Workbook.createWorkbook(file);
	WritableSheet ws = wwb.createSheet("Test Shee 1", 0);
	Label famicode = new Label(0, 0, "家庭编号");      
	Label perscode = new Label(1, 0, "农合证号");
	Label payTime = new Label(2, 0, "缴费时间");
	Label payCost = new Label(3, 0, "缴费金额");
	Label creator = new Label(4, 0, "代办人");
	ws.addCell(famicode);
	ws.addCell(perscode);
	ws.addCell(payTime);
	ws.addCell(payCost);
	ws.addCell(creator);
	Payment dao=new Payment();
	List<Payment> list=null;
	String famid=req.getParameter("id");
	String persid=req.getParameter("perscode");
	//req.getParameter("perscode");
	 list=dao.print(famid,persid,flag);
	int i=0;
    for(Payment p:list){
	    String famcode=p.getFamicode();
	    String percode=p.getPerscode();
	    String time=p.getPaytime().toString();
	    String cost=Double.toString(p.getPayCost());
	    String creat=p.getCreator();
		Label famcode_i = new Label(0, i + 1, famcode);
		Label percode_i = new Label(1, i + 1, percode);
		Label time_i = new Label(2, i + 1, time);
		Label cost_i = new Label(3, i + 1, cost);
		Label creat_i = new Label(4, i + 1, creat);

		ws.addCell(famcode_i);
		ws.addCell(percode_i);
		ws.addCell(time_i);
		ws.addCell(cost_i);
		ws.addCell(creat_i);
		i++;
		
		}

    wwb.write();
	// 关闭Excel工作簿对象
	System.out.println("数据导出成功!");
	wwb.close();
	
	
	
}
}
